package com.hdaccp.shuiguoD.shiro;


import com.hdaccp.shuiguoD.dao.RoleDao;
import com.hdaccp.shuiguoD.dao.userDao;
import com.hdaccp.shuiguoD.entity.Role;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private userDao userDao ;
    @Autowired
    private RoleDao roleDao ;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权方法...");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo() ;
        String uname = (String) principalCollection.getPrimaryPrincipal() ;
        Role role = roleDao.getRoleByUserName(uname) ;
        System.out.println(role.getRcode() + "------------------------------");
        info.addRole(role.getRcode());
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken ;
        String uname = token.getUsername() ;
        //1.根据用户名从数据库表中获取用户的密码
        String upwd = userDao.getPwdByUserName(uname) ;
        if(upwd==null || "".equals(upwd)){
            return  null ;
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(uname,upwd,ByteSource.Util.bytes("Shiro"),"myrealm") ;
        return info;
    }
}
